package com.windfone.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.windfone.common.FileTool;
 
/**
 * 文件上传的Servlet，我们使用Apache组织提供的commons-fileupload.jar和commons-io.jar包实现文件上传功能
 * @author Administrator
 *
 */
public class FileUploadServlet extends HttpServlet {
 
    /** Constructor of the object.   */
    public FileUploadServlet() {
        super();
    }
 
    /** Destruction of the servlet. */
    public void destroy() {
        super.destroy();
    }
 
    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request, response);
    }
 
    
     
    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        OutputStream os = null;
        FileInputStream is = null;
        try {
        UploadBean fileBean = new UploadBean();
        String tmpFile = this.getServletContext().getRealPath("/");
        File file = new File(tmpFile  + "temp"); 
        if (!file.exists()) {
          file.mkdirs();
        }
        
        fileBean.setObjectPath(tmpFile  + "temp"+File.separator);
        fileBean.setSourceFile(request);
        String uploadFolder =fileBean.getFieldValue("uploadFolder");
        String fileName = fileBean.getObjectFileName()[0];

        String root = tmpFile+"upload"+File.separator	+ uploadFolder+File.separator;
        File tmp = new File(root);
		if ( !tmp.exists())
			tmp.mkdirs();
		
        root = FileTool.getFolderPath(root, 0,false);
		File diskFile = new File(root,fileName  );
		String returnPic = diskFile.getAbsolutePath();
		int begin = returnPic.indexOf("upload");
		returnPic = returnPic.substring(begin, returnPic.length() );
		returnPic = returnPic.replace("\\", "/");
		
		File inputFile = new File(tmpFile + "temp"+File.separator +fileName);
		is = new FileInputStream(inputFile);
		os = new FileOutputStream(diskFile);      
		byte[] buffer = new byte[400];
		int length = 0;
		while ((length = is.read(buffer)) > 0) {
			os.write(buffer, 0, length);
		}
		if (inputFile.exists())
			inputFile.delete();
		out.println("<script>parent.callback('upload file success|"+ returnPic +"')</script>");
        }catch(Exception e){
        	e.printStackTrace();
        	out.println("<script>parent.callback('upload file error')</script>");
        }finally {
        	if ( os !=null )
        		os.close();
        	if ( is !=null )
        		is.close();
        }
//        final long maxSize = 1024 * 1024 * 5; //定义文件允许上传的大小
////        final String[] fileExtType = {"jpg" , "JPG" , "gif", "doc" , "docx"}; //定义允许上传文件后缀名
//        DiskFileItemFactory disk = new DiskFileItemFactory(); //设置实例化一个硬盘工厂
//        disk.setSizeThreshold(5120); //设置上传文件时临时存放文件到内存缓存区的大小为5kb
//        String tmpFile = this.getServletContext().getRealPath("/");
//        System.out.println("临时上传文件路径：" + tmpFile);
//        File file = new File(tmpFile + "/" + "temp"); //在javaweb下面建立一个tmpFile文件，该文件用于存放上传时候的临时文件夹
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        disk.setRepository(file); //设置缓存的路径或目录
//        ServletFileUpload sfu = new ServletFileUpload(disk); //初始化上传文件的核心类ServletFileUpload
//        sfu.setSizeMax(maxSize); //设置文件允许上传的大小
//        List list = null; //List列表用于存储上传文件表单域中的所有上传值
//        try {
//            list = sfu.parseRequest(request); //解析请求过来的上传文件表单域，通过将域中的所有值放到List中
//        } catch (FileUploadException e) {
//            e.printStackTrace();
//            if (e instanceof SizeLimitExceededException) {
//                out.println("上传文件超过5M");
//                out.println("<script language='javascript'>");
//                out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件超过5M</font>';");
//                out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
//                out.println("</script>");
//                return;
//            }
//        }
//         
//        Iterator iterator = list.iterator();
//        while (iterator.hasNext()) {
//            FileItem fileItem = (FileItem) iterator.next();
//            if (fileItem.isFormField()) { //判断是否是一个普遍的表单域，true则表示是普遍表单域而不是文件域
////                String fieldName = fileItem.getFieldName();
////                String value = fileItem.getString("utf-8");
//            } else {
////                String fileFieldName = fileItem.getFieldName(); //获取文件域的名称
////                System.out.println("文件域的名称：" + fileFieldName);
//                String fileName = fileItem.getName(); //上传文件的名称，包括全路径
//                System.out.println("上传文件的名称：" + fileName);
//                long fileSize = fileItem.getSize(); //上传文件的大小
//                System.out.println("上传文件的大小：" + fileSize);
//                 
//                
//                
//                
//                String root = tmpFile;//ServletActionContext.getServletContext().getRealPath("/");
//				// 3.获得一个本地文件
//                 
//                
//                String uploadFolder ="null";//getFolderName(request.getInputStream());
//                String returnPic="";
//				root = root+"upload"+File.separator	+ uploadFolder+File.separator;
//				File tmp = new File(root);
//				if ( !tmp.exists())
//					tmp.mkdirs();
//				
//				String fileUploadName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
//				root = FileTool.getFolderPath(root, 0,false);
//				File diskFile = new File(root, fileUploadName);
//				returnPic = diskFile.getAbsolutePath();
//				int begin = returnPic.indexOf("upload");
//				returnPic = returnPic.substring(begin, returnPic.length() );
//				returnPic = returnPic.replace("\\", "/");                
//                
//                
//                
////                
////                file = new File(tmpFile + "\\" + "fileUploadDir");
////                if (!file.exists()) {
////                    file.mkdirs();
////                }
////                 
//                FileOutputStream fos = new FileOutputStream(diskFile);//(tmpFile + "\\" + "fileUploadDir" + "\\" + fileUploadName);
//                 
//                if (fileItem.isInMemory()) { //判断上传的文件是否已经在内存中
//                    try {
//                        fos.write(fileItem.get());
//                        out.println("上传文件" + fileUploadName + "成功");
//                    } catch (IOException e) {
//                        out.println("上传文件失败");
//                        return;
//                    } finally {
//                        fos.close();
//                    }
//                     
//                } else {
//                    InputStream is = fileItem.getInputStream(); //获取上传文件内容的输入流
//                    int i = 0;
//                    byte[] b = new byte[1024 * 4];
//                    try {
//                        while ((i = is.read(b)) != -1) {
//                            fos.write(b, 0, i);
//                        }
//                        out.println("上传文件：" + fileUploadName + "成功");
//                        out.println("<script language='javascript'>");
//                        out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件成功</font>';");
//                        out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
//                        out.println("</script>");
//                        out.println("<script>parent.callback('upload file success|"+ returnPic +"')</script>");
//                    } catch (IOException e) {
//                        out.println("上传文件失败");
//                        out.println("<script language='javascript'>");
//                        out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件失败</font>';");
//                        out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
//                        out.println("</script>");
//                        out.println("<script>parent.callback('upload file error')</script>");
//                    } finally {
//                        is.close();
//                        fos.close();
//                    }
//                }
//            }
//        }
//        out.flush();
//        out.close();
    }
 
    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException {
    }
 
}
